package org.example.repository;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;
import java.util.Objects;

@Slf4j
public class OnDriverCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalOnDriver.class.getName());
        // log.info("{}", attributes);

        if (attributes == null) {
            return false;
        }

        boolean matchIfMissing = (boolean) attributes.get("matchIfMissing");
        String expected = (String) attributes.get("value");
        String actual = context.getEnvironment().getProperty("driver");

        if (matchIfMissing && (actual == null || actual.isEmpty())) {
            return true;
        }
        return Objects.equals(expected, actual);
    }
}
